package common.Forum;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Locale;
import java.util.concurrent.ExecutionException;

import type.TaskDescriptions;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.PixelFormat;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.ContextMenu;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.project.institute.DAO.InstituteListFragmentDAO;
import com.project.trac.R;

import core.modules.DatabaseConnector;

public class ViewThread extends InstituteListFragmentDAO implements TaskDescriptions {
	
	private View parent;
	private TextView spiel;
	private EditText textBox;
	private Dialog dialog;
	private AlertDialog.Builder alertDialog;
	
	private int forumID;
	private String TITLE;
	private String SECTION;
	
	private final int CONTEXT_MENU_READ = 1;
	private final int CONTEXT_MENU_DROP = 2;
	
	public static ListFragment newInstance(Context context) {
		
		ViewThread lf = new ViewThread();
		return lf;
	}

	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		return (ViewGroup) inflater.inflate(R.layout.generic_list, null);
	}

	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		TITLE = getActivity().getIntent().getExtras().getString("TITLE");
		
		OnItemClickListener click = new OnItemClickListener(){

			@Override
			public void onItemClick(AdapterView<?> av, View view, int position, long id) {
				
				String item = av.getItemAtPosition(position).toString().replace("=", "");
				forumID = Integer.valueOf(item.substring(item.indexOf("forumID")+7, item.indexOf(", content")));
				registerForContextMenu(av);
				getActivity().openContextMenu(av);
			}
			
		};

		getListView().setOnItemClickListener(click);

	}
	
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
		menu.setHeaderTitle("Select an Action");
		menu.add(Menu.NONE, CONTEXT_MENU_READ, Menu.NONE, "Reply to Thread");
			
		if (getRole() == 0) {
			menu.add(Menu.NONE, CONTEXT_MENU_DROP, Menu.NONE, "Delete thread");
		}
		
	}
	
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		
		switch (item.getItemId()) {

		case CONTEXT_MENU_READ:
			replytoThread();
			break;
		case CONTEXT_MENU_DROP:
			deleteThread();
			break;
		}

		return super.onContextItemSelected(item);
	}
	
	public void onBackPressed() {
		super.getActivity().onBackPressed();
	}

	public void onResume() {
		try {
			SECTION = new AsynchronousTask().execute(INITIALIZE).get();
		} catch (InterruptedException e) {
			DatabaseConnector.Logger(getClass(), "AsynchronousTask - Initialize", e);
		} catch (ExecutionException e) {
			DatabaseConnector.Logger(getClass(), "AsynchronousTask - Initialize", e);
		} catch (NullPointerException e) {
			DatabaseConnector.Logger(getClass(), "AsynchronousTask - Initialize", e);
		}
		
		super.onResume();
	}
	
	public void onAttachedToWindow() {
		super.getActivity().onAttachedToWindow();
		Window window = getActivity().getWindow();
		window.setFormat(PixelFormat.RGBA_8888);
	}
	
	void replytoThread() {
		
		parent = View.inflate(getActivity(), R.layout.generic_dialog_box, null);
		alertDialog = new AlertDialog.Builder(getActivity());
	    alertDialog.setCancelable(false);
		
		textBox = (EditText) parent.findViewById(R.id.et_dialog_input);
		spiel = (TextView) parent.findViewById(R.id.tv_dialog_spiel);
		spiel.setText("");
		
		textBox.setHeight(140);
		textBox.setLines(20);
		textBox.setMaxLines(50);
		textBox.setSingleLine(false);
		textBox.setGravity(Gravity.LEFT | Gravity.TOP);
		
		alertDialog.setPositiveButton("Publish", new DialogInterface.OnClickListener(){

			@Override
			public void onClick(DialogInterface dialog, int which) {
				if (textBox.getText().length() != 0) {
					
					new AsynchronousTask().execute(REPLY);
					
					Toast.makeText(getActivity().getApplicationContext(), "reply published!", Toast.LENGTH_SHORT).show();
					((ViewGroup) parent.getParent()).removeView(parent);
				} else {
					textBox.setError("must not be empty!");
				}
				
			}});
		
		alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener(){

			@Override
			public void onClick(DialogInterface dialog, int which) {
				((ViewGroup) parent.getParent()).removeView(parent);
				dialog.dismiss();
			}});
		
		
		dialog = alertDialog.setTitle("Compose reply").setView(parent).create();
		dialog.show();
	}
	
	void deleteThread() {
		
		parent = View.inflate(getActivity(), R.layout.generic_dialog_box, null);
		alertDialog = new AlertDialog.Builder(getActivity());
	    alertDialog.setCancelable(false);
	    
		textBox = (EditText) parent.findViewById(R.id.et_dialog_input);
		spiel = (TextView) parent.findViewById(R.id.tv_dialog_spiel);
		spiel.setVisibility(View.GONE);
		textBox.setVisibility(View.GONE);
		
		alertDialog.setPositiveButton("Delete", new DialogInterface.OnClickListener(){
				@Override
				public void onClick(DialogInterface dialog, int which) {
					new AsynchronousTask().execute(DROP);
					Toast.makeText(getActivity().getApplicationContext(), "thread deleted", Toast.LENGTH_SHORT).show();
					((ViewGroup) parent.getParent()).removeView(parent);
					dialog.dismiss();
			}
		});
		
		alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener(){
				@Override
				public void onClick(DialogInterface dialog, int which) {
					((ViewGroup) parent.getParent()).removeView(parent);
					dialog.dismiss();
				}
		});
		
		
		if (getRole() == 0) {
			alertDialog.setTitle("Really delete " + TITLE + "?");
		} else {
			alertDialog.setTitle("Really delete?");
		}
		
		dialog = alertDialog.setView(parent).create();
		dialog.show();
	}
	
	private class AsynchronousTask extends AsyncTask<String, String, String> {

		HashMap<String, String> m;
		ArrayList<HashMap<String, String>> arrayList = new ArrayList<HashMap<String, String>>();

		ProgressDialog progressDialog;
		ListAdapter listAdapter;

		String KEY_DATE_STARTED = "start";
		String KEY_CONTENT = "content";
		String KEY_FORUM_ID = "forumID";

		protected void onPreExecute() {
			super.onPreExecute();
			progressDialog = new ProgressDialog(getActivity());
			progressDialog.setMessage("please wait..");
			progressDialog.setIndeterminate(true);
			progressDialog.setCancelable(true);
			progressDialog.show();

		}

		protected String doInBackground(String... args) {

			try {
				if (args[0].equalsIgnoreCase(INITIALIZE)) {
					ResultSet rs = DatabaseConnector.getStatement().executeQuery(
							"SELECT id, section, title, content, DATE_FORMAT(date_started,'%Y-%b-%d') AS 'start' "
							+ " FROM forum WHERE isThread = 2 AND cid = " + getSubjectID());

					while (rs.next()) {
						m = new HashMap<String, String>();
						m.put(KEY_DATE_STARTED, rs.getString("start"));
						m.put(KEY_CONTENT, rs.getString("content"));
						m.put(KEY_FORUM_ID, rs.getString("id"));
						arrayList.add(m);
						
						return  rs.getString("section");
					}
					
				}
				
				if (args[0].equalsIgnoreCase(REPLY)) {
					java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
					
					DatabaseConnector.getConnection().setAutoCommit(false);
					DatabaseConnector.setPreparedStatement("INSERT INTO forum (uid, cid, sid, section, content, replyto_id, replyto_date, isThread) VALUES (?,?,?,?,?,?,?,?)");
					PreparedStatement pps = DatabaseConnector.getPreparedStatement();
					pps.setInt(1, getUserID());
					pps.setInt(2, getSubjectID());
					pps.setInt(3, getScheduleID());
					pps.setString(4, SECTION);
					pps.setString(5, textBox.getText().toString());
					pps.setInt(6, forumID);
					pps.setString(7, sdf.format(Calendar.getInstance().getTime()).toString());
					pps.setInt(8, 3);

					pps.executeUpdate();
					pps.close();
					
					getActivity().runOnUiThread(new Runnable() {

						@Override
						public void run() {
							startActivity(getActivity().getIntent());
							getActivity().finish();
						}
					});
				}
				
				if (args[0].equalsIgnoreCase(DROP)) {
					DatabaseConnector.getConnection().setAutoCommit(false);
					PreparedStatement id = DatabaseConnector.getConnection().prepareStatement("DELETE FROM forum WHERE id = ?");
					PreparedStatement rid = DatabaseConnector.getConnection().prepareStatement("DELETE FROM forum WHERE replyto_id = ?");
					
					id.setInt(1, forumID); 		id.executeUpdate(); 	id.close();
					rid.setInt(1, forumID); 	rid.executeUpdate(); 	id.close();
					
					getActivity().runOnUiThread(new Runnable() {

						@Override
						public void run() {
							startActivity(getActivity().getIntent());
							getActivity().finish();
						}
					});
				}
				
			} catch (SQLException e) {
				DatabaseConnector.Logger(getClass(), "doInBackground", e);
			}

			return null;
		}

		protected void onPostExecute(String postExecute) {

			progressDialog.dismiss();

			getActivity().runOnUiThread(new Runnable() {

				@Override
				public void run() {

					listAdapter = new SimpleAdapter(getActivity(), arrayList, R.layout.common_forum_header_detail, 
							new String[] {KEY_DATE_STARTED, KEY_CONTENT, KEY_FORUM_ID}, 
							new int[] {R.id.tv_title, R.id.tv_content});

					setListAdapter(listAdapter);
				}
			});
		}
	} 

}